import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/sqlite_db';

// This route proxies PHP requests for development
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { 
      application_form_summary, 
      code_summary, 
      document_summary,
      module,
      serial_number 
    } = body;
    
    // Check if we're generating a specific module or all modules
    if (module) {
      // Single module generation
      const summaryKey = `${module}_summary`;
      const summaryValue = body[summaryKey];
      
      if (!summaryValue) {
        return NextResponse.json({
          success: false,
          error: '缺少必要参数'
        });
      }

      // Simulate successful response for single module
      const fullKey = `${module}_full`;
      const mockResponse = {
        [fullKey]: `${summaryValue}

[完整版本内容]
这里是完整的${getModuleTitle(module)}内容，包含详细的专业描述和符合要求的格式化内容。`
      };

      // Update database if serial_number is provided
      if (serial_number) {
        try {
          const sql = `
            UPDATE generation_record
            SET ${fullKey} = ?, status = 'completed'
            WHERE serial_number = ?
          `;
          await query(sql, [mockResponse[fullKey], serial_number]);
        } catch (dbError) {
          console.error('Database update error:', dbError);
        }
      }

      return NextResponse.json({
        success: true,
        data: mockResponse
      });
    } else {
      // All modules generation
      if (!application_form_summary || !code_summary || !document_summary) {
        return NextResponse.json({
          success: false,
          error: '缺少必要参数'
        });
      }

      // Simulate successful response with mock data
      const mockResponse = {
        application_form_full: `${application_form_summary}

[完整版本内容]
这里是完整的登记申请表内容，包含页眉页脚、页码格式，以及符合登记要求的详细内容。`,
        
        code_full: `${code_summary}

[完整版本内容]
这里是完整的源程序材料，包含详细的技术描述、代码结构和实现说明。`,
        
        document_full: `${document_summary}

[完整版本内容]
这里是完整的说明文档内容，包含详细的设计说明、操作指南和技术文档。`
      };

      // Update database if serial_number is provided
      if (serial_number) {
        try {
          const sql = `
            UPDATE generation_record
            SET application_form_full = ?, code_full = ?, document_full = ?, status = 'completed'
            WHERE serial_number = ?
          `;
          await query(sql, [
            mockResponse.application_form_full,
            mockResponse.code_full,
            mockResponse.document_full,
            serial_number
          ]);
        } catch (dbError) {
          console.error('Database update error:', dbError);
        }
      }

      return NextResponse.json({
        success: true,
        data: mockResponse
      });
    }

  } catch (error) {
    console.error('Generate full error:', error);
    return NextResponse.json({
      success: false,
      error: '生成失败: ' + (error as Error).message
    });
  }
}

function getModuleTitle(module: string) {
  const titles = {
    application_form: '登记申请表',
    code: '源程序',
    document: '说明文档'
  };
  return titles[module as keyof typeof titles] || module;
}